package com.bbx.taxi.client.Util;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.bbx.api.util.LogUtils;

/**
 *主要用于ScrollView嵌套ListView，ListView不能自适应高度问题,前提适配器的布局为LinearLayout
 */
public class ListViewHeight {
	/**
	 *主要用于ScrollView嵌套ListView，ListView不能自适应高度问题,前提适配器的布局为LinearLayout
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) { 
	    if(listView == null) return;

	    ListAdapter listAdapter = listView.getAdapter(); 
	    if (listAdapter == null) { 
	        // pre-condition 
	        return; 
	    } 

	    int totalHeight = 0; 
	    for (int i = 0; i < listAdapter.getCount(); i++) { 
	        View listItem = listAdapter.getView(i, null, listView); 
	        listItem.measure(0, 0); 
	        totalHeight += listItem.getMeasuredHeight(); 
	    } 

	    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
	    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 
	    listView.setLayoutParams(params); 
	}
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	public static void seGridViewHeightBasedOnChildren(Context context,GridView gridView,int layout) {
		if(gridView == null) return;

		ListAdapter listAdapter = gridView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}
		//测量下gridView.getNumColumns()才不会等于-1
		int width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
		int height =View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
          //measure一次才能获取到属性值
		gridView.measure(width,height);
		float numColumns=gridView.getNumColumns();
		int verticalSpacing=gridView.getVerticalSpacing();
		int rows= (int) Math.ceil(listAdapter.getCount()/numColumns);
		View view = (ViewGroup) LayoutInflater.from(context).inflate(layout,null);
        int view_height=MeasureViewUtils.getMeasuredHeight(view);
		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		params.height = view_height*rows+(verticalSpacing*(rows-1));
		LogUtils.e("log", params.height+"");
		gridView.setLayoutParams(params);
	}
}
